//
//  ProfileViewController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/8.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
/// 个人中心
class ProfileViewController: BaseViewController {
    
    private let updateUrl = "https://apps.apple.com/cn/app/id6448246991"
    
    @IBOutlet weak var versionLabel: UILabel!{
        didSet{
            versionLabel.text = (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String)!
        }
    }
    private var viewModel: ProfileViewModel? {
        didSet {
            updateData()
        }
    }
    @IBOutlet weak var phoneLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        HUDTool.showActivity()
        

        
        let bgLayer1 = CAGradientLayer()
        bgLayer1.colors = [UIColor(red: 0.89, green: 0.93, blue: 1, alpha: 1).cgColor, UIColor(red: 0.96, green: 0.97, blue: 0.99, alpha: 0.7).cgColor, UIColor(red: 1, green: 1, blue: 1, alpha: 1).cgColor]
        bgLayer1.locations = [0, 0.34, 1]
        
        let backview = UIView(frame: view.frame)
        view.addSubview(backview)
        bgLayer1.frame = view.bounds
        bgLayer1.startPoint = CGPoint(x: 0.5, y: 0.01)
        bgLayer1.endPoint = CGPoint(x: 1, y: 1)
        backview.layer.addSublayer(bgLayer1)

        view.sendSubviewToBack(backview)
        
        
        let infoTap = UITapGestureRecognizer(target: self, action: #selector(personInfo))
        infoView.addGestureRecognizer(infoTap)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: true)
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NotiName.loginSuccess, object: nil)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        setNavClear()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        setNavWhite()
        navigationController?.setNavigationBarHidden(false, animated: true)
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
//        contentViewWContrains.constant = screenW
//        contentViewHContrains.constant = lastLabel.bottom + 30 + 20
    }
    
    override func makeUI() {
        super.makeUI()
        
        if !UserDefaults.username.isEmpty {
            nameLabel.text = UserDefaults.username
        }
        if !UserDefaults.account.isEmpty {
            phoneLabel.text = ""// UserDefaults.account
        }
       
        let placeholder = UserDefaults.usersex == "男" ? UIImage(named: "avatar_male") : UIImage(named: "avatar_female")
        avatarView.kf.setImage(with: URL(string: UserDefaults.userAvatar), placeholder: placeholder)
        
        loadData()
    }
    
    private func loadData() {
        
        ProfileViewModel.getOrderNumbers(userId: UserDefaults.userId) { (datas, error) in
            HUDTool.hideActivity()
            if error == nil && !datas.isEmpty {
                self.viewModel = ProfileViewModel(datas: datas)
            } else {
               // HUDTool.showError(message: error == "token验证服务关闭" ? "请先登录" : error)
            }
        }
    }
    
    private func updateData() {
        guard let vm = viewModel else { return }
        topHeaderView.configure(with: vm)
    }
    
    @IBOutlet weak var avatarView: UIImageView! {
        didSet {
            avatarView.contentMode = .scaleAspectFill
            avatarView.layer.cornerRadius = avatarView.height / 2
            avatarView.layer.masksToBounds = true
        }
    }
    
    @IBOutlet private weak var nameLabel: UILabel!
    
    @IBOutlet private weak var contentViewWContrains: NSLayoutConstraint!
    @IBOutlet private weak var contentViewHContrains: NSLayoutConstraint!
    
    @IBOutlet private weak var infoView: UIView!
    
    @IBOutlet private weak var topHeaderView: ProfileHeaderView! {
        didSet {
            topHeaderView.delegate = self
        }
    }
    
    @IBOutlet private weak var prescriptionOrderView: ProfileCellView! {
        didSet {
            prescriptionOrderView.delegate = self
        }
    }
    
    @IBOutlet private weak var familyView: ProfileCellView! {
        didSet {
            familyView.delegate = self
        }
    }
    
    @IBOutlet weak var regiatrationView: ProfileCellView! {
        didSet {
            regiatrationView.delegate = self
        }
    }
    
    @IBOutlet weak var versionCellView: ProfileCellView!{
        didSet {
            versionCellView.delegate = self
        }
    }
    
    @IBOutlet private weak var helpCenterView: ProfileCellView! {
        didSet {
            helpCenterView.delegate = self
        }
    }

}

// MARK: - Action
extension ProfileViewController {
    @IBAction private func callPhoneAction(_ sender: UIButton) {
        guard let title = sender.title(for: .normal),
            let phoneUrl = URL(string: "tel://\(title)") else { return }
        if UIApplication.shared.canOpenURL(phoneUrl) {
            UIApplication.shared.open(phoneUrl, options: [:], completionHandler: nil)
        }
    }
    
    @objc private func personInfo() {
        Utilities.pushLoginVc(self)
        
        let infoVc = YSGPersonInfoViewController(name: UserDefaults.username,
                                                 avatar: UserDefaults.userAvatar)
        navigationController?.pushViewController(infoVc, animated: true)
    }
    
    @objc private func loginSuccess() {
        self.makeUI()
    }
}

// MARK: - ProfileCellViewDelegate
extension ProfileViewController: ProfileCellViewDelegate {
    func cellView(didTapped view: ProfileCellView) {
        if view == prescriptionOrderView {
            
           // pushPrescriptionOrderVc()
        } else if view == familyView {
            pushFamilyVc()
        } else if view == helpCenterView {
            pushHelpCenterVc()
        } else if view == regiatrationView {
            pushRegistration()
        } else if view == versionCellView{
            checkVersion()
        }else {
            pushSettingVc()
        }
    }
    
    private func pushRegistration() {
        let vc = RegistrationRecordsController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    private func pushFamilyVc() {
        let familyVc = FamilyViewController()
        familyVc.fromProfile = true
        navigationController?.pushViewController(familyVc, animated: true)
    }
    

    
    /// 弹出更新提示
    public func checkVersion() {
        
        guard let updateURL = URL(string: updateUrl) else { return }
        YSGAppManager.getAppStoreAppVersion { (version, forceUpdate, code) in
            switch code {
            case .failure:
                HUDTool.show(message: "当前版本已是最新")
                break
            case .success:
                if forceUpdate {
                    AlertTool.showAlert(self, title: "您有新版本(v\(version))更新", sureTitle: "去更新", sureHandler: { _ in
                        if UIApplication.shared.canOpenURL(updateURL) {
                            UIApplication.shared.open(updateURL, options: [:], completionHandler: nil)
                        }
                    })
                } else {
                    AlertTool.showAlert(self, title: "您有新版本(v\(version))更新", sureTitle: "现在更新", cancelTitle: "取消", type: .double, sureHandler: { _ in
                        if UIApplication.shared.canOpenURL(updateURL) {
                            UIApplication.shared.open(updateURL, options: [:], completionHandler: nil)
                        }
                    }, cancelHandler: nil)
                }
            }
        }
    }
    
    private func pushSettingVc() {
        let settingVc = SettingViewController()
        navigationController?.pushViewController(settingVc, animated: true)
    }
    
    /// 跳转帮助中心
    private func pushHelpCenterVc() {
        let helpCenterVc = YSGHelpCenterViewController()
        navigationController?.pushViewController(helpCenterVc, animated: true)
    }
}

extension ProfileViewController: ProfileHeaderViewDelegate {
    
    func headerView(allOrderDidTapped view: ProfileHeaderView, type: YSGDiagnoseType) {
        if topHeaderView == view {
            //  pushInquiryOrderVc(status: 0, type: 1)
        }
    }
    //图文咨询
    func headerView(firstDidTapped view: ProfileHeaderView, type: YSGDiagnoseType) {
        if topHeaderView == view {
            pushInquiryOrderVc(status: 0, type: .advisory)
        }
    }
    //云门诊
    func headerView(secondDidTapped view: ProfileHeaderView, type: YSGDiagnoseType) {

        pushInquiryOrderVc(status: 0, type:.cloud)
    }
    //我的护理
    func headerView(thirdDidTapped view: ProfileHeaderView, type: YSGDiagnoseType) {
//        let status = type == .advisory ? 4 : 3
//        pushInquiryOrderVc(status: status, type: type)
        pushAppointmentOrderVc()
        
    }
    //我的药品
    func headerView(fourthDidTapped view: ProfileHeaderView, type: YSGDiagnoseType) {
        pushPrescriptionOrderVc()
    }
    
    private func pushInquiryOrderVc(status: Int, type: YSGDiagnoseType) {
        let index = type == .advisory ? 1 : 0
        let inquiryVc = MyInquiryController(with: status, startIndex: index)
        navigationController?.pushViewController(inquiryVc, animated: true)
    }
    
    private func pushPrescriptionOrderVc() {
        let orderVc = PrescriptionOrderController()
        navigationController?.pushViewController(orderVc, animated: true)
    }
    private func pushAppointmentOrderVc() {
        let orderVc = YSGNurseAppointmentOrderPageViewController()
        navigationController?.pushViewController(orderVc, animated: true)
    }
    
    
}

